package com.test.springsecurity.controller;

import com.test.springsecurity.entity.AppUser;
import com.test.springsecurity.service.AuthService;
import com.test.springsecurity.util.JWTUtil;
import com.test.springsecurity.util.ResponseResult;
import com.test.springsecurity.util.ResultStatus;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * 提供自定义登录的接口，因为前后端分离项目 中springsecurity内置的登录逻辑不太适合
 */
@RestController
@RequestMapping("/auth")
public class AuthController {

    @Resource
    private AuthService authService;

    @PostMapping("login")
    public ResponseResult<Object> login(@RequestBody AppUser user, HttpServletResponse response){
        boolean result = authService.login(user);

        ResponseResult<Object> responseResult = new ResponseResult<>();

        if(result){
            responseResult.setCode(200);
            responseResult.setMessage("登录成功");
            responseResult.setResultStatus(ResultStatus.SUCCESS);

            //生成token
            String token = JWTUtil.generateToken(user.getUsername());

            //将token放到响应头中 程序员都习惯用authentication作为token的名字
            response.addHeader("authorization",token);

            //springboot中如果要自定义响应头 则需要暴露该头 如果不暴露 前端代码就无法获取到该信息
            response.setHeader("Access-Control-Expose-Headers","authorization");

        }else {
            responseResult.setCode(401);
            responseResult.setMessage("账号密码有误");
            responseResult.setResultStatus(ResultStatus.FAIL);
        }
        return responseResult;
    }
}
